<template>
  <el-dialog
    :visible.sync="visible"
    :before-close="handleCloseDiablog"
    width="50%"
    title="编辑权限">
    <ul class="menu-list">
      <li v-for="item in allMenuList" :key="item.menu_id">
        <el-checkbox v-model="item.checked">{{ item.menu_name }}</el-checkbox>
      </li>
    </ul>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCloseDiablog">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getAllMenuList, getRoleMenuList, updateRoleMenu } from '@/api/user'

export default {
  name: 'EditMenuDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      props: {
        value: 'label',
        children: 'cities'
      },
      allMenuList: []
    }
  },
  watch: {
    visible: function(value) {
      if (value) {
        this.getList()
      } else {
        this.allMenuList = []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList(data) {
      getAllMenuList().then(allMenu => {
        getRoleMenuList(this.roleId).then(roleMenu => {
          this.allMenuList = this.formateMenuList(allMenu.data, roleMenu.data)
        })
        // this.allMenuList = res.data
      }).catch(() => {})
    },
    formateMenuList(all, role) {
      const result = all
      result.map(item => {
        if (role.some(h => item.menu_id === h.menu_id)) {
          item.checked = true
        }
      })
      return result
    },
    handleSubmit() {
      const params = { roleId: this.roleId }
      params.menuIds = this.formateIDs(this.allMenuList)

      updateRoleMenu(params).then(res => {
        if (res.code === 200) {
          this.$message('保存成功')
          this.handleCloseDiablog()
        }
      })
    },
    handleCloseDiablog() {
      this.$emit('close')
    },
    formateIDs(data) {
      const res = []
      data.forEach(item => {
        if (item.checked) {
          res.push(item.menu_id)
        }
      })
      return res.join(',')
    }
  }
}
</script>

<style lang="scss" scoped>
.menu-list {
  li {
    display: inline-block;
    width: 200px;
  }
}
</style>
